/**
  ******************************************************************************
  * @file           : rs71_usb_receiver.h
  * @author         : wangyingjie
  * @brief          : None
  * @attention      : None
  * @date           : 2025/6/20
  ******************************************************************************
  */

#ifndef RS71_USB_RECEIVER_H
#define RS71_USB_RECEIVER_H

#ifndef CAN_DEVICE_H
#define CAN_DEVICE_H

#include <vector>
#include <string>
#include <mutex>

#ifdef WIN32
#include <windows.h>
#include <process.h>
typedef HANDLE ThreadHandle;
#define THREAD_RETURN unsigned __stdcall
#else
#include <pthread.h>
#include <unistd.h>
#define THREAD_RETURN void*
typedef pthread_t ThreadHandle;
#endif

#include "controlcan.h"

#define RX_BUFF_SIZE 1000
#define RX_WAIT_TIME 100

class RS71UsbReceiver
{
public:
    RS71UsbReceiver(unsigned devType, unsigned devIdx, unsigned chMask, unsigned baud);

    ~RS71UsbReceiver();

    bool init(unsigned devType, unsigned devIdx, unsigned chMask, unsigned baud);

    bool Open();

    void Close();

    bool Start();

    void Stop();

    struct CanFrame
    {
        unsigned int id;
        unsigned int timestamp;
        std::vector<unsigned char> data;
    };

    std::vector<CanFrame> GetReceivedData(unsigned channel);

private:
    struct RX_CTX
    {
        unsigned channel;
        volatile bool stop;
        std::vector<CanFrame> buffer;
        std::mutex mtx;
    };

    static THREAD_RETURN RxThreadFunc(void *param);

    unsigned devType, devIdx, chMask, baud;
    RX_CTX rxContexts[4];
    ThreadHandle rxThreads[4];

#ifdef WIN32
  static unsigned __stdcall RxThreadWrapper(void* param);
#endif
};

#endif


#endif //RS71_USB_RECEIVER_H
